package com.imflea.zero.filter;

import com.imflea.zero.constant.QxContant;
import com.imflea.zero.utils.SessionUtils;
import com.imflea.zero.util.ZeroCacheUtils;
import com.imflea.zero.util.ZeroJsonUtils;
import com.imflea.zero.util.base.CommonUtils;;
import com.imflea.zero.util.base.JsonResult;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.Map;

/**
 * @author 祥保玉
 * @PackageName: com.imflea.zero.filter
 * @ClassName: AuthticationFilter
 * @Description
 * @date 2021-08-23  14:58:31
 */
public class AuthticationFilter implements Filter {
    private String ignorePattern;

    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        this.ignorePattern = filterConfig.getInitParameter("ignorePattern");
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;
        response.setHeader("Access-Control-Allow-Origin", "*");
        response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
        response.setHeader("Access-Control-Max-Age", "3600");
        response.setHeader("Access-Control-Allow-Headers",
                "Content-Type, Content-Length, Authorization, Accept, X-Requested-With , yourHeaderFeild");
        response.setHeader("Access-Control-Allow-Credentials", "true");


        if (isRequestUrlExcluded(request)) {
            filterChain.doFilter(request, response);
            return;
        } else {
            Map<String, String> headersInfo = CommonUtils.getHeadersInfo(request);
            String accessToken = headersInfo.get(QxContant.getWebAccessTokenKey().toLowerCase());
            try {
                if (CommonUtils.isNull(accessToken)) {
                    //返回401,请求登录
                    JsonResult<Map<String, Object>> result = new JsonResult<>();
                    result.setCode("401");
                    response.setStatus(401);
                    response.getWriter().write(ZeroJsonUtils.entityToJson(result));
                    return;
                }

                String cacheTokenMap = ZeroCacheUtils.getString(QxContant.getLoginTokenPrefix() + accessToken);


                if (CommonUtils.isNull(cacheTokenMap)) {
                    //返回401,请求登录
                    JsonResult<Map<String, Object>> result = new JsonResult<>();
                    result.setCode("401");
                    response.setStatus(401);
                    response.getWriter().write(ZeroJsonUtils.entityToJson(result));
                    return;
                }
                Map<String, Object> tokenInfo =ZeroJsonUtils.jsonToMap(cacheTokenMap);
                if (CommonUtils.isNull(tokenInfo)) {
                    //返回401,请求登录
                    JsonResult<Map<String, Object>> result = new JsonResult<>();
                    result.setCode("401");
                    response.getWriter().write(ZeroJsonUtils.entityToJson(result));
                    return;
                } else {
                   ZeroCacheUtils.expire(QxContant.getLoginTokenPrefix() + accessToken, QxContant.getSessionTime());
                    SessionUtils.makeSession(tokenInfo, request);
                    filterChain.doFilter(request, response);
                }
            } catch (Exception e) {
                e.printStackTrace();
                //返回401,请求登录
                e.printStackTrace();
                response.setStatus(500);
                response.setContentType("text/hmtl;charset=utf-8");
                response.getWriter().append("业务异常,请联系管理员！");
                return;
            }
        }

    }

    @Override
    public void destroy() {

    }

    private boolean isRequestUrlExcluded(HttpServletRequest request) {
        StringBuffer urlBuffer = request.getRequestURL();
        if (request.getQueryString() != null) {
            urlBuffer.append("?").append(request.getQueryString());
        }
        String requestUri = urlBuffer.toString();
        String pattern = ".*(swaggerCheck|swagger-ui|swagger-resources|webjars|springfox|api-docs|v4|csrf).*";

        return (requestUri.matches(this.ignorePattern) || requestUri.matches(pattern));
    }
}
